<template>
	<s-layout title="特价商品">
   
    <view
      class="ss-flex ss-flex-wrap ss-p-x-20 ss-m-t-20 "
    >
      <view class="goods-list-box">
        <view class="left-list" v-for="(item,index)  in state.leftGoodsList" :key="item.id">
          <s-goods-column
            class="goods-md-box"
            size="md"
			:goodsFields="state.fields"
            :data="item"
            :topRadius="10"
            :bottomRadius="10"
			  :titleWidth="300"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
            @getHeight="mountMasonry($event, 'left')"
          >
            <template v-slot:cart>
				
				<view class="catView" >
										<!-- <button class="ss-reset-button cart-btn" /> -->
					<button v-if="item.skuIds[0].cartCount == 0" class="ss-reset-button cart-btn carbutton"  @click.stop="onleftclickcart(index)">
					     购物车
					 </button>
					 
					 <view  v-if="item.skuIds[0].cartCount != 0" class="ss-reset-button cart-btn">
					  <su-number-box :min="0" :max="item.skuIds[0].purchaseMaximum > -1 ? item.skuIds[0].purchaseMaximum : 9999" :step="1" :value='item.skuIds[0].cartCount'
					    @change="onleftNumberChange($event, index)" />
					 </view> 
				</view>
             
            </template>
          </s-goods-column>
        </view>
      </view>
      <view class="goods-list-box">
        <view class="right-list" v-for="(item,index)  in state.rightGoodsList" :key="item.id">
          <s-goods-column
		    v-if="item.type===2"
            class="goods-md-box"
            size="md"
            :topRadius="10"
            :bottomRadius="10"
            :data="item"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
            @getHeight="mountMasonry($event, 'right')"
          >
           <template v-slot:cart>
		 	<view class="catView" >
				  <button v-if="item.skuIds[0].cartCount == 0" class="ss-reset-button cart-btn carbutton"  @click.stop="onrightclickcart(index)">
				       购物车
				   </button>
                 <view  v-if="item.skuIds[0].cartCount != 0" class="ss-reset-button cart-btn">
                  <su-number-box :min="0" :max="item.skuIds[0].purchaseMaximum > -1 ? item.skuIds[0].purchaseMaximum : 9999" :step="1" :value='item.skuIds[0].cartCount'
                    @change="onrightNumberChange($event, index)" />
                 				</view>  
								
			   </view> 
            </template>
			
          </s-goods-column>
        </view>
      </view>
    </view>
  <!--  <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadMore"
    /> -->
	
    <s-empty v-if="state.pagination.length === 0" icon="/static/soldout-empty.png" text="暂无商品" />
  </s-layout>
</template>

<script setup>
  import { computed , reactive } from 'vue';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import _ from 'lodash-es';
  import { resetPagination } from '@/sheep/util';
   import $store from '@/sheep/store';
  import SpuApi from '@/sheep/api/product/spu';
  import CartApi from '@/sheep/api/trade/cart';
 import { showAuthModal, showShareModal } from '@/sheep/hooks/useModal';
  const sys_navBar = sheep.$platform.navbar;
  const emits = defineEmits(['close', 'change']);
  const userInfo = computed(() => sheep.$store('user').userInfo);
  const state = reactive({
    pagination: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 6,
    },
	fields:{
		introduction: {show: true, color: "#999"},
		marketPrice: {show: true, color: "#c4c4c4"},
		name: {show: true, color: "#000"},
		price: {show: true, color: "#ff3000"},
		salesCount: {show: true, color: "#c4c4c4"},
		stock: {show: false, color: "#c4c4c4"},
		
	},
    showFilter: false,
    iconStatus: false, // true - 单列布局；false - 双列布局
    keyword: '',
    categoryId: 0,
    loadStatus: '',
    leftGoodsList: [], // 双列布局 - 左侧商品
    rightGoodsList: [], // 双列布局 - 右侧商品
  });

  // 加载瀑布流
  let count = 0;
  let leftHeight = 0;
  let rightHeight = 0;
  
  const props = defineProps({
    data: {
      type: Object,
      default: () => ({}),
    },
    styles: {
      type: Object,
      default: () => ({}),
    },
  });
  const { layoutType, btnBuy, spuIds } = props.data || {};
  const { marginLeft, marginRight } = props.styles || {};


async function onleftclickcart (e){
  	 
  	  
  	 // 页面登录拦截
  	 if (!$store('user').isLogin) {
  	 	  // console.log("denglMode")
  	   showAuthModal();
  	   return;
  	 }
	
	 const { data, code } = await CartApi.addCart({
	   skuId: state.leftGoodsList[e].skuIds[0].skuId,
	   count: state.leftGoodsList[e].skuIds[0].purchaseMinimum,
	 });
	 // 刷新购物车列表
	 if (code === 0) {
	 		
	 	 state.leftGoodsList[e].skuIds[0].cartCount = data
	 		
	     sheep.$store('cart').getList();	
	 }
  	 	 
   };
  
 
  async function onleftNumberChange(e,index){
  	  
  	  
  	  if (e === state.leftGoodsList[index].skuIds[0].purchaseMinimum-1) {
  	    		       
  	   
  	   const { data, code } = await CartApi.deleteByCart({
  	     skuId:state.leftGoodsList[index].skuIds[0].skuId,
  	   
  	   });

  	   // 刷新购物车列表
  	   if (code === 0) {
  	   		
  	   		 state.leftGoodsList[index].skuIds[0].cartCount =  0
  	   		
  	         sheep.$store('cart').getList();	
  	   }
  	   
  	  }else{
		  	  
		  var ge = {	    
		     goods_num: e,
		     id: state.leftGoodsList[index].skuIds[0].skuId,	  	    		  
		  }
		  sheep.$store('cart').add(ge);
		  
	  }
  	   	  
  };
   
 async function onrightclickcart (e){
	  	    
  	 // 页面登录拦截
  	 if (!$store('user').isLogin) {
  	 	  // console.log("denglMode")
  	   showAuthModal();
  	   return;
  	 }
	 
	 	
	 const { data, code } = await CartApi.addCart({
	   skuId: state.rightGoodsList[e].skuIds[0].skuId,
	   count: state.rightGoodsList[e].skuIds[0].purchaseMinimum,
	 });
	 // 刷新购物车列表
	 if (code === 0) {
	 		
	 	 state.rightGoodsList[e].skuIds[0].cartCount = data
	 		
	     sheep.$store('cart').getList();	
	 }
	  
   	 
   };
  
  async function onrightNumberChange(e,index){
	  
	  
	  
	    console.log(e)
	  if (e === state.rightGoodsList[index].skuIds[0].purchaseMinimum-1) {
	    		       
	   
	   const { data, code } = await CartApi.deleteByCart({
	     skuId:state.rightGoodsList[index].skuIds[0].skuId,
	   
	   });
	   // 刷新购物车列表
	   if (code === 0) {
	   		
	   		 state.rightGoodsList[index].skuIds[0].cartCount =  0
	   		
	         sheep.$store('cart').getList();	
	   }
	   
	    	
	   
	   	return;
	  }else{
	  		  
	  		  
	  		  var ge = {
	  		    
	  		     goods_num: e,
	  		     id: state.rightGoodsList[index].skuIds[0].skuId,	  
	  		    		  
	  		  }
	  		  sheep.$store('cart').add(ge);
	  		  
	  }
	    
	  
  };
  // 处理双列布局 leftGoodsList + rightGoodsList
  function mountMasonry(height = 0, where = 'left') {
    if (!state.pagination.list[count]) {
      return;
    }

    if (where === 'left') {
      leftHeight += height;
    } else {
      rightHeight += height;
    }
    if (leftHeight <= rightHeight) {
      state.leftGoodsList.push(state.pagination.list[count]);
    } else {
      state.rightGoodsList.push(state.pagination.list[count]);
    }
    count++;
  }


  async function getList() {
    state.loadStatus = 'loading';
    const { code, data } = await SpuApi.getSpuPage({
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
      sortField: state.currentSort,
      sortAsc: state.currentOrder,
      categoryId: state.categoryId,
      keyword: state.keyword,
	    userId:userInfo.value.id
    });
    if (code !== 0) {
      return;
    }
	
	console.log(data)
    state.pagination.list = _.concat(state.pagination.list, data.list);
    state.pagination.total = data.total;
    state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
    mountMasonry();
  }

  // 加载更多
  function loadMore() {
    if (state.loadStatus === 'noMore') {
      return;
    }
    state.pagination.pageNo++;
    getList(state.currentSort, state.currentOrder);
  }
  
   async function getGoodgsactivity(ids) {


		const {
			code,
			data
		} = await SpuApi.getSpuListactivity();
		if (code !== 0) {
			return;
		}
		
		getGoodsListSpecialSaleProducts(data.specialSaleProducts);
	}


async function getGoodsListSpecialSaleProducts(specialSaleProducts) {

		// state.loadStatus = 'loading';
		const {
			code,
			data
		} = await SpuApi.getSpuListByIds(specialSaleProducts.join(','));
		if (code !== 0) {
			return;
		}
              
			  console.log(data)
            state.pagination.list = _.concat(state.pagination.list, data);
			
			  console.log(state.pagination.list)
			 mountMasonry();
		// 			state.specialSaleProducts = _.concat(state.specialSaleProducts, state.specialSaleProducts);
		// state.pagination.total = data.total;
		// state.loadStatus = state.goodsList.length < state.pagination.total ? 'more' : 'noMore';


	}


  onLoad((options) => {
	  
	  console.log(options)
	  // tjgetlist()
    // state.categoryId = options.categoryId;
    // state.keyword = options.keyword;
	
	getGoodgsactivity()
    // getList(state.currentSort, state.currentOrder);
  });

  // 上拉加载更多
  onReachBottom(() => {
    loadMore();
  });
</script>

<style lang="scss" scoped>
 .goods-list-box {
     width: 50%;
     box-sizing: border-box;
 
     .left-list {
       margin-right: 10rpx;
       margin-bottom: 20rpx;
     }
 
     .right-list {
       margin-left: 10rpx;
       margin-bottom: 20rpx;
     }
   }
 
   .goods-box {
     &:nth-last-of-type(1) {
       margin-bottom: 0 !important;
     }
 
     &:nth-child(2n) {
       margin-right: 0;
     }
   }
 
   .list-icon {
     width: 80rpx;
 
     .sicon-goods-card {
       font-size: 40rpx;
     }
 
     .sicon-goods-list {
       font-size: 40rpx;
     }
   }
 
   .goods-card {
     margin-left: 20rpx;
   }
 
   .list-filter-tabs {
     background-color: #fff;
   }
 
   .catView {
 	  
 	  display: flex;
 	  justify-content: flex-end;
 	  padding-right: 8rpx;
 	  // width: 100%;
 	  padding-bottom: 20rpx;
   }
 
   .carbutton{
 	  
 	  
 	    
 		    color: white;
 		    height: 50rpx;
 			width: 50%;
 		    line-height: 50rpx;
 		    border-radius: 25rpx;
 	        background: linear-gradient(to right,#FF6000 ,#FE832A );
 	  
   }
   
   .lgcarbutton{
 	  
 	  color: white;
 	  // height: 50rpx;
 	  // width: 50%;
 	  font-size: 20rpx;
 	  line-height: 50rpx;
 	  border-radius: 25rpx;
 	  background: linear-gradient(to right,#FF6000 ,#FE832A );
   }
</style>
